package main

import (
	"fmt"
	"math/rand"
	"mod10homework/src/metrics"
	"time"

	"github.com/prometheus/client_golang/prometheus/promhttp"
	"log"
	"net/http"
	"os"
	"strings"
)

func main() {
	metrics.Register()

	http.HandleFunc("/", rootHandler)
	http.HandleFunc("/healthz", healthHandler)

	//添加一个handler
	http.Handle("/metrics", promhttp.Handler())

	err := http.ListenAndServe(":8080", nil)
	if err != nil {
		log.Fatal("ListenAndServe: ", err)
	}
}

func rootHandler(w http.ResponseWriter, r *http.Request) {
	//每次被访问时，就会给NewLatency新实例传入一个当前时间值和绑定的直方图实例，并且在方法返回前，进行时间差的计算后传入直方图实例
	fmt.Println("-------new visit-------")
	latency := metrics.NewLatency()
	defer latency.ObserveTotal()

	if strings.Compare(r.URL.String(), "/") != 0 {
		fmt.Println("客户端 ", r.RemoteAddr, " 访问不存在url: ", r.URL.String())
		w.WriteHeader(404)
		return
	}

	//模拟延时
	rand.Seed(time.Now().UnixNano())
	delay := rand.Intn(2000)
	fmt.Println("-------delay: ", delay, "ms")
	time.Sleep(time.Millisecond * time.Duration(delay))

	for s, v := range r.Header {
		w.Header().Add(s, v[0])
	}
	w.Header().Set("Version", os.Getenv("VERSION"))
	hostIP := r.RemoteAddr
	fmt.Println(hostIP)
	StatusCode := 200
	w.WriteHeader(StatusCode)
	fmt.Println("客户端IP = ", strings.Split(hostIP, ":")[0], "	HTTP返回码 = ", StatusCode)
}

func healthHandler(w http.ResponseWriter, r *http.Request) {
	w.WriteHeader(200)
}
